package ans.pjz_offer_55___ii;

import ans.base.TreeNode;
import test.Entrance;

/**
 * #      剑指 Offer 55 - II
 * 名称   平衡二叉树
 * 链接   https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof
 * 题解   [660](https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution)
 * 通过率 58.2%
 * 难道   简单
 */

public class Solution {
    @Entrance
    public boolean isBalanced(TreeNode root) {
        boolean res[] = new boolean[]{true};
        deep(root, res);
        return res[0];
    }

    public int deep(TreeNode root, boolean res[]) {
        if (root == null || res[0] == false) {
            return 0;
        }
        int dl = deep(root.left, res);
        int dr = deep(root.right, res);
        if (Math.abs(dl - dr) > 1) {
            res[0] = false;
            return 0;
        } else {
            return Math.max(dl, dr) + 1;
        }
    }
}